/**
 * File:		ClientSocket.java
 * Project:		Virtual Advisor
 * Module:		ClientSocket
 * Author:		Rotem Ganel
 * Created:		Apr 24, 2011
 * Updated:		Apr 24, 2011
 * Version:		1 (in progress)
 * 
 * Adapted from Oracle Java Socket Tutorial
 * http://www.oracle.com/technetwork/java/socket-140484.html#server
 */
package clientSocket;

import java.io.*;
import java.net.*;

import javax.swing.JOptionPane;

//Testing only
import clientApp.CourseRecord;

class ClientPortal	{
	private static Socket socket = null;
	private static ObjectOutputStream serializer = null;
	private static ObjectInputStream unpacker = null;
	
	public static void instantiate() throws UnknownHostException, IOException {
		instantiate("0.0.0.0", 2222);
	}
	
	public static void instantiate(String address, int port) throws UnknownHostException, IOException {
//		InetAddress IP = InetAddress.getByName(address);
//		socket = new Socket(IP, port);
		try {
			socket = new Socket(address, port);
		} catch (ConnectException e) {
			JOptionPane.showMessageDialog(null, "Server is down.");
			System.exit(-1);
		}
		
		serializer = new ObjectOutputStream(socket.getOutputStream());
		unpacker = new ObjectInputStream(socket.getInputStream());
	}
	
	public static void sendObject(Object object) throws IOException {
		//TODO: throw error if not instantiated
		serializer.writeObject(object);
//		System.out.println("Successfully sent");
	}
	
	public static Object receiveData() throws IOException, ClassNotFoundException {
		//TODO: throw error if not instantiated
		Object o = unpacker.readObject();
//		System.out.println("Successfully recieved.");
		return o;
	}
	
	public static void terminate() throws IOException {
		//TODO: throw error if not instantiated
		serializer.flush();
		serializer.close();
		unpacker.close();
		socket.close();
	}

   public static void main(String[] args) throws ClassNotFoundException	{
	   try {
		   ClientPortal.instantiate();
		   CourseRecord sampleCourse = new CourseRecord("CMSC 201", 'B', "");
		   ClientPortal.sendObject(sampleCourse);

		   String serverInput;
		   while ((serverInput = ((String)ClientPortal.receiveData())) != null) {
//			    System.out.println(serverInput);
			}

		   ClientPortal.terminate();
	   } catch (IOException e) {
//		  System.out.println(e);
	   }
   }
}

